package main

import (
	"fmt"
	"time"
)


func worker(i int, c chan int) {
	for {  //方式一
		n, ok := <-c
		if !ok {
			break
		}
		fmt.Printf("Worker %d received %d\n", i, n)
	}

	for n := range c { //方式二
		fmt.Printf("Worker %d received %d\n", i, n)
	}
}

func createWorker(i int) chan<- int {
	c := make(chan int)   // 加入两个或多个发送（创建）channel的   那么  怎么让指定的channel去接收呢？
	go func() {
		for {
			fmt.Printf("CreateWorker %d received %c\n", i, <-c)
		}
	}()
	return c
}

func chanDemo() {
	c := make(chan int)
	go func() {
		for {
			n := <-c
			fmt.Println(n)
		}
	}()

	c <- 1
	c <- 2
	c <- 3
	c <- 4
	c <- 5
	c <- 6
	time.Sleep(time.Millisecond * 10)
	c <- 7
	c <- 8
	c <- 9
	c <- 10
	c <- 11
	c <- 12
	c <- 13
}


func chanDemos() {
	var channels [10]chan int
	for i := 0; i < 10; i++ {
		channels[i] = make(chan int)
		go worker(i, channels[i])
	}

	for i := 0; i < 10; i++ {
		channels[i] <- 'a' + i
	}
	time.Sleep(time.Millisecond)
}

func chanDemo1() {
	var channels [10]chan<- int
	for i := 0; i < 10; i++ {
		channels[i] = createWorker(i)
	}

	for i := 0; i < 10; i++ {
		channels[i] <- 'A' + i
	}
	time.Sleep(time.Millisecond)
}

func bufferdChannel() {
	c := make(chan int, 3) //后面的是缓冲区
	go worker(0, c)
	c <- 'a'
	c <- 'b'
	c <- 'c'
	//c <- 'd'
	time.Sleep(time.Millisecond)
}

func channelClose() {
	c := make(chan int)
	go worker(0, c)
	c <- 'a'
	c <- 'b'
	c <- 'c'
	c <- 'd'
	close(c)
	time.Sleep(time.Millisecond)
}

func main() {
	//chanDemo()
	//chanDemos()
	//chanDemo1()
	channelClose()
}
